<?php

namespace App\Miya\Middlewares;

use Closure;

class UrlRejectDomain
{
    protected $tag = '/uploads/uploads/';

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        //剔除url中的域名
        if (
            $request->has('action') &&
            $request->input('action') == "upload-image"
        ) {
            $json = $response->content();
            $data = json_decode($json, true);
            if ($data['state'] == 'SUCCESS') {
                $data['url'] = sprintf(
                    '%s%s',
                    $this->tag,
                    explode($this->tag, $data['url'])[1]
                );
                $response->setData($data);
            }
        }

        return $response;
    }
}
